export default async function compressImage(image: HTMLImageElement, maxThrottle: number, minQuality = 0.1, options: any) {
    if (typeof image !== "object" || !(image instanceof HTMLImageElement)) {
        throw '请传入正确的HTMLImageElement类型的对象';
    }
    const canvas: HTMLCanvasElement = document.createElement('canvas');
    const destType = 'image/jpeg';
    let sizeCompressTimes = 0;
    let qualityCompressTimes = 0;
    let endRatio = 1;
    let endQuality = 0.92;

    async function compressSize(ratio = 1): Promise<Blob> {
        endRatio = ratio;
        console.log(`ratio:${ratio}`);
        if (ratio < 0.2) {
            throw `已经超出了压缩的最低限制：${ratio}了`;
        }
        try {
            canvas.width = image.width * ratio;
            canvas.height = image.height * ratio;
            canvas.getContext('2d')?.drawImage(image, 0, 0, canvas.width, canvas.height);
            return await tools(minQuality, 0.92);
        } catch (e) {
            if (options.debug) {
                console.warn(e);
            }
            sizeCompressTimes++;
            return await compressSize(ratio * 0.9);
        }
    }

    async function tools(min: number, max: number): Promise<Blob> {
        if (max < min) {
            throw "无法压缩到对应目标大小";
        }
        const blob = await getBlob(max);
        if (blob.size < maxThrottle) {
            endQuality = max;
            return blob;
        }
        const minBlob = await getBlob(min);
        if (minBlob.size > maxThrottle) {
            throw "无法压缩到目标大小";
        }
        qualityCompressTimes++;
        return tools(min, max - 0.1);
    }

    function getBlob(qulity = 0.92): Promise<Blob> {
        return new Promise((resolve) => {
            canvas.toBlob((blob) => {
                if (blob) {
                    resolve(blob);
                } else {
                    throw new Error("无法由canvas获取图片二进制数据");
                }
            }, destType, qulity);
        });
    }

    let timeStart = new Date().getTime();
    let result = await compressSize();
    let timeEnd = new Date().getTime();
    if (options && options.debug) {
        console.log(`尺寸压缩的次数为：${sizeCompressTimes}`);
        console.log(`质量压缩的次数为：${qualityCompressTimes}`);
        console.log(`要求的大小为：${maxThrottle}`);
        console.log(`最终大小为：${result.size}`);
        console.log(`最终的尺寸压缩比例为：${endRatio}`);
        console.log(`最终的quality为：${endQuality}`);
        console.log(`总执行用时为：${timeEnd - timeStart}`);
        alert(JSON.stringify({
            sizeCompressTimes,
            qualityCompressTimes,
            maxThrottle,
            size: result.size,
            endRatio,
            endQuality,
            time: timeEnd - timeStart
        }));
    }
    return result;
}
